const axios = require('axios');

// 测试配置
const BASE_URL = 'http://localhost:3000/api';
let authToken = '';
let testUserId = 'testuser123';
let testUsername = '测试用户';
let testPassword = 'testpass123';

// 测试数据
let testWriterId = null;
let testWorkId = null;
let testQuoteId = null;

// 颜色输出函数
const colors = {
  green: '\x1b[32m',
  red: '\x1b[31m',
  yellow: '\x1b[33m',
  blue: '\x1b[34m',
  reset: '\x1b[0m'
};

function log(message, color = 'reset') {
  console.log(`${colors[color]}${message}${colors.reset}`);
}

// 测试工具函数
async function testAPI(name, testFunction) {
  try {
    log(`\n${'='.repeat(50)}`, 'blue');
    log(`测试: ${name}`, 'blue');
    log(`${'='.repeat(50)}`, 'blue');
    
    await testFunction();
    log(`✅ ${name} - 测试通过`, 'green');
  } catch (error) {
    log(`❌ ${name} - 测试失败: ${error.message}`, 'red');
    if (error.response) {
      log(`   状态码: ${error.response.status}`, 'red');
      log(`   响应: ${JSON.stringify(error.response.data)}`, 'red');
    }
  }
}

// 1. 用户注册测试
async function testUserRegistration() {
  const response = await axios.post(`${BASE_URL}/register`, {
    userId: testUserId,
    username: testUsername,
    password: testPassword
  });
  
  if (response.status === 201) {
    log('用户注册成功', 'green');
  }
}

// 2. 用户登录测试
async function testUserLogin() {
  const response = await axios.post(`${BASE_URL}/login`, {
    userId: testUserId,
    password: testPassword
  });
  
  if (response.status === 200 && response.data.token) {
    authToken = response.data.token;
    axios.defaults.headers.common['Authorization'] = `Bearer ${authToken}`;
    log('用户登录成功，Token已设置', 'green');
  }
}
// 3. 获取作家列表测试
async function testGetWriters() {
  const response = await axios.get(`${BASE_URL}/writers`);
  
  if (response.status === 200 && Array.isArray(response.data.writers)) {
    log(`获取作家列表成功，共${response.data.total}个作家`, 'green');
  }
}

// 4. 创建作家测试
const FormData = require('form-data');
const fs = require('fs');

async function testCreateWriter() {
  const form = new FormData();
  form.append('name', '测试作家');
  form.append('experience', '这是一个测试作家的生平介绍');
  const response = await axios.post(`${BASE_URL}/writers`, form, {
    headers: {
      'x-auth-token': authToken,
      'Content-Type': 'multipart/form-data'
    }
  });
  if (response.status === 201 && response.data.id) {
    testWriterId = response.data.id;
    log(`创建作家成功，ID: ${testWriterId}`, 'green');
  }
}
// 5. 获取作家详情测试
async function testGetWriterDetail() {
  if (!testWriterId) {
    throw new Error('没有可用的作家ID');
  }
  
  const response = await axios.get(`${BASE_URL}/writers/${testWriterId}`);
  
  if (response.status === 200 && response.data.id === testWriterId) {
    log('获取作家详情成功', 'green');
  }
}

// 6. 创建作品测试
async function testCreateWork() {
  if (!testWriterId) {
    throw new Error('没有可用的作家ID');
  }
  
  const formData = new FormData();
  formData.append('title', '测试作品');
  formData.append('writer_id', testWriterId);
  formData.append('is_biography', '0');
  formData.append('detail_link', 'https://example.com');
  
  const response = await axios.post(`${BASE_URL}/works`, formData, {
    headers: {
      'x-auth-token': authToken,
      'Content-Type': 'multipart/form-data'
    }
  });
  
  if (response.status === 201 && response.data.id) {
    testWorkId = response.data.id;
    log(`创建作品成功，ID: ${testWorkId}`, 'green');
  }
}

// 7. 获取作品列表测试
async function testGetWorks() {
  const response = await axios.get(`${BASE_URL}/works/all`);
  
  if (response.status === 200 && Array.isArray(response.data)) {
    log(`获取作品列表成功，共${response.data.length}个作品`, 'green');
  }
}

// 8. 创建名言测试
async function testCreateQuote() {
  if (!testWriterId) {
    throw new Error('没有可用的作家ID');
  }
  
  const response = await axios.post(`${BASE_URL}/quotes`, {
    content: '这是一句测试名言',
    writer_id: testWriterId
  }, {
    headers: {
      'x-auth-token': authToken,
      'Content-Type': 'application/json'
    }
  });
  
  if (response.status === 201 && response.data.id) {
    testQuoteId = response.data.id;
    log(`创建名言成功，ID: ${testQuoteId}`, 'green');
  }
}

// 9. 获取名言列表测试
async function testGetQuotes() {
  const response = await axios.get(`${BASE_URL}/quotes/all`);
  
  if (response.status === 200 && Array.isArray(response.data)) {
    log(`获取名言列表成功，共${response.data.length}个名言`, 'green');
  }
}

// 10. 更新作家信息测试
async function testUpdateWriter() {
  if (!testWriterId) {
    throw new Error('没有可用的作家ID');
  }
  
  const response = await axios.put(`${BASE_URL}/writers/${testWriterId}`, {
    name: '更新后的测试作家',
    experience: '这是更新后的生平介绍'
  }, {
    headers: {
      'x-auth-token': authToken,
      'Content-Type': 'application/json'
    }
  });
  
  if (response.status === 200 && response.data.name === '更新后的测试作家') {
    log('更新作家信息成功', 'green');
  }
}

// 11. 更新作品信息测试
async function testUpdateWork() {
  if (!testWorkId) {
    throw new Error('没有可用的作品ID');
  }
  
  const response = await axios.put(`${BASE_URL}/works/${testWorkId}`, {
    title: '更新后的测试作品',
    is_biography: '0',
    detail_link: 'https://updated-example.com'
  }, {
    headers: {
      'x-auth-token': authToken,
      'Content-Type': 'application/json'
    }
  });
  
  if (response.status === 200 && response.data.title === '更新后的测试作品') {
    log('更新作品信息成功', 'green');
  }
}

// 12. 更新名言测试
async function testUpdateQuote() {
  if (!testQuoteId) {
    throw new Error('没有可用的名言ID');
  }
  
  const response = await axios.put(`${BASE_URL}/quotes/${testQuoteId}`, {
    content: '这是更新后的测试名言'
  }, {
    headers: {
      'x-auth-token': authToken,
      'Content-Type': 'application/json'
    }
  });
  
  if (response.status === 200 && response.data.content === '这是更新后的测试名言') {
    log('更新名言成功', 'green');
  }
}

// 13. 删除名言测试
async function testDeleteQuote() {
  if (!testQuoteId) {
    throw new Error('没有可用的名言ID');
  }
  
  const response = await axios.delete(`${BASE_URL}/quotes/${testQuoteId}`, {
    headers: {
      'x-auth-token': authToken
    }
  });
  
  if (response.status === 200) {
    log('删除名言成功', 'green');
  }
}

// 14. 删除作品测试
async function testDeleteWork() {
  if (!testWorkId) {
    throw new Error('没有可用的作品ID');
  }
  
  const response = await axios.delete(`${BASE_URL}/works/${testWorkId}`, {
    headers: {
      'x-auth-token': authToken
    }
  });
  
  if (response.status === 200) {
    log('删除作品成功', 'green');
  }
}

// 15. 删除作家测试
async function testDeleteWriter() {
  if (!testWriterId) {
    throw new Error('没有可用的作家ID');
  }
  
  const response = await axios.delete(`${BASE_URL}/writers/${testWriterId}`, {
    headers: {
      'x-auth-token': authToken
    }
  });
  
  if (response.status === 200) {
    log('删除作家成功', 'green');
  }
}

// 16. 搜索功能测试
async function testSearchWriters() {
  const response = await axios.get(`${BASE_URL}/writers?search=测试`);
  
  if (response.status === 200) {
    log(`搜索作家成功，找到${response.data.total}个结果`, 'green');
  }
}

// 17. 分页功能测试
async function testPagination() {
  const response = await axios.get(`${BASE_URL}/writers?page=1&pageSize=2`);
  
  if (response.status === 200 && response.data.writers.length <= 2) {
    log('分页功能测试成功', 'green');
  }
}

// 18. 随机作家功能测试
async function testRandomWriter() {
  const response = await axios.get(`${BASE_URL}/writers/random`);
  
  if (response.status === 200 && response.data.id) {
    log('获取随机作家成功', 'green');
  }
}

// 19. 权限控制测试 - 未授权访问
async function testUnauthorizedAccess() {
  try {
    await axios.post(`${BASE_URL}/writers`, {
      name: '未授权测试'
    });
    throw new Error('应该返回401错误');
  } catch (error) {
    if (error.response && error.response.status === 401) {
      log('权限控制测试成功 - 未授权访问被正确拒绝', 'green');
    } else {
      throw error;
    }
  }
}

// 20. 输入验证测试
async function testInputValidation() {
  try {
    await axios.post(`${BASE_URL}/writers`, {
      name: '', // 空名称
      experience: '测试'
    }, {
      headers: {
        'x-auth-token': authToken,
        'Content-Type': 'application/json'
      }
    });
    throw new Error('应该返回400错误');
  } catch (error) {
    if (error.response && error.response.status === 400) {
      log('输入验证测试成功 - 空名称被正确拒绝', 'green');
    } else {
      throw error;
    }
  }
}

// 主测试函数
async function runAllTests() {
  log('开始API测试...', 'yellow');
  
  // 基础功能测试
  await testAPI('用户注册', testUserRegistration);
  await testAPI('用户登录', testUserLogin);
  await testAPI('获取作家列表', testGetWriters);
  await testAPI('创建作家', testCreateWriter);
  await testAPI('获取作家详情', testGetWriterDetail);
  await testAPI('创建作品', testCreateWork);
  await testAPI('获取作品列表', testGetWorks);
  await testAPI('创建名言', testCreateQuote);
  await testAPI('获取名言列表', testGetQuotes);
  
  // 更新功能测试
  await testAPI('更新作家信息', testUpdateWriter);
  await testAPI('更新作品信息', testUpdateWork);
  await testAPI('更新名言', testUpdateQuote);
  
  // 高级功能测试
  await testAPI('搜索功能', testSearchWriters);
  await testAPI('分页功能', testPagination);
  await testAPI('随机作家功能', testRandomWriter);
  
  // 安全性测试
  await testAPI('权限控制测试', testUnauthorizedAccess);
  await testAPI('输入验证测试', testInputValidation);
  
  // 删除功能测试（最后执行）
  await testAPI('删除名言', testDeleteQuote);
  await testAPI('删除作品', testDeleteWork);
  await testAPI('删除作家', testDeleteWriter);
  
  log('\n🎉 所有测试完成！', 'green');
}

// 运行测试
runAllTests().catch(error => {
  log(`测试过程中发生错误: ${error.message}`, 'red');
  process.exit(1);
}); 